#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>

#include "../Comm/util.hpp"
#include "../Comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;

    class Compiler
    {
    public:
        Compiler()
        {
        }

        static bool Compile(const std::string &filename)
        {
            pid_t id = fork();
            if (id < 0)
            {
                LOG(ERROR) << "编译时创建子进程失败" << "\n";
                return false;
            }
            else if (id == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompileError(filename).c_str(), O_CREAT | O_WRONLY, 0644);
                if (_stderr < 0)
                {
                    LOG(WARNINR) << "没有成功创建stderr文件" << "\n";
                    exit(-1);
                }

                dup2(_stderr, 2);
                execlp("g++", "g++", "-o", PathUtil::Exe(filename).c_str(), PathUtil::Src(filename).c_str(), "-std=c++11", nullptr);
                LOG(ERROR) << "启动编译器g++失败，可能是参数错误" << "\n";
                exit(-2);
            }
            else
            {
                waitpid(id, nullptr, 0);
                if (FileUtil::IsFileExists(PathUtil::Exe(filename)))
                {
                    LOG(INFO) << PathUtil::Src(filename) << " 编译成功!" << "\n";
                    return true;
                }
                LOG(ERROR) << "编译失败，没有形成可执行程序" << "\n";
                return false;
            }
        }

        ~Compiler()
        {
        }
    };
}